import { Layout, DatePicker, Table, Tag, message, Button, Modal, Input } from 'antd';
import axios from 'axios'
import { useCallback, useEffect, useState } from 'react';
import './App.css'
import { ColumnsType } from 'antd/es/table';
import moment from 'moment';

const { Header, Content } = Layout;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

interface columnDef {
  title: string,
  className: string,
  dataIndex: string,
  align: string,
}
interface Record {
  userName: string,
  workLong: number,
  extraWorkLong: number,
  shiftInfo: string,
  day: Date
}
const statusEnum:any = {
  'NOTCLOCKIN_AFTERNOON': {
    text: '下班缺卡',
    color: '#f50'
  },
  'OUT_WORK': {
    text: '外勤',
    color: '#2db7f5'
  },
  'REST': {
    text: '休息',
    color: 'gold'
  },
  'NORMAL': {
    text: '正常',
    color: '#87d068'
  }
}
const weekEnum:any = {
  0: '周日',
  1: '周一',
  2: '周二',
  3: '周三',
  4: '周四',
  5: '周五',
  6: '周六',
}
const columns: ColumnsType<columnDef> = [
  {
    title: '姓名',
    dataIndex: 'userName',
    fixed: 'left',
    width: 100,
  },
  {
    title: '工作日期',
    dataIndex: 'day',
    fixed: 'left',
    width: 150,
    render: day => {
      return moment(day).format('YYYY-MM-DD') + ' ' + weekEnum[moment(day).format('d')]; 
    }
  },
  {
    title: '班次',
    dataIndex: 'shiftInfo'
  },
  {
    title: '内勤工时',
    dataIndex: 'workLong',
  },
  {
    title: '外勤工时',
    dataIndex: 'extraWorkLong',
  },
  {
    title: '出勤状态',
    dataIndex: 'status',
    render: status => (
      <span>
        {status.map((item:string) => {
          const {color, text} = statusEnum[item]
          return (
            <Tag color={color} key={text}>
              {text}
            </Tag>
          );
        })}
      </span>
    ),
  },
  {
    title: '反馈已确认',
    dataIndex: 'ackCount'
  },
  {
    title: '反馈未确认',
    dataIndex: 'notAckCount'
  },
  {
    title: '反馈信息',
    dataIndex: 'feedbackMsg'
  }
]

const dateFormat = 'YYYY-MM-DD';

function App() {
  const [tableData, setTableData] = useState([])
  const [loading, setLoading] = useState(false)
  const [totalTime, setTotalTime] = useState(0)
  const [nomalWorkDay, setNomalWorkDay] = useState(0)
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [cookie, setCookie] = useState('')

  const currentMonth = moment().format('YYYY-MM')
  const startDate =  moment(`${currentMonth}-01`).format(dateFormat)
  const endDate = moment().format(dateFormat)
  const [searchParams, setSearchParams] = useState({ startDate, endDate })

  const getList = useCallback(async () => {        
    setLoading(true) 
    const body = {
      userId: "60d53a80e4b05021e357a60d",
      status: null,
      page: 1,
      limit: 31,
      total: null,
      sort: "-day",
      ...searchParams
    };
    const { data } = await axios.post('http://localhost:3003/attendances', { ...body } )
    let totalTime = 0
    let nomalWorkDay = 0
    const { code, errorMsg } = data
    const today = moment().format(dateFormat)
    if (code === 200) {
      data.data.list.forEach((el:Record) => {
        if (el.shiftInfo === '管易(09:00-18:00)' && moment(el.day).format(dateFormat) !== today) {
          nomalWorkDay ++
        }
        totalTime = totalTime + el.workLong + el.extraWorkLong
      });
      setTableData(data.data.list)
    } else {
      message.error(errorMsg)
      setTableData([])
    }
    setTotalTime(totalTime)
    setNomalWorkDay(nomalWorkDay)
    setLoading(false) 
  }, [searchParams])

  useEffect(() => {
    getList()
  }, [getList])

  let param = { startDate: '', endDate: '' }
  function handleDateChange(date:any) {
    if (date) {
      const startDate =  moment(date[0]).format(dateFormat)
      const endDate = moment(date[1]).format(dateFormat)
      param = { startDate, endDate }
    } else {
      setSearchParams({ startDate: '', endDate: '' })
    }
  }

  const handleOpenChange = (open:Boolean) => {
    if (!open) {
      setSearchParams(param)
    }
  }

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    setIsModalVisible(false);
    const data = await axios.post('http://localhost:3003/setCookie', { cookie } )
    message.success(data.data)
    getList()
  };

  const handleCancel = () => {
    setCookie('')
    setIsModalVisible(false);
  };

  const onChange = (e: any) => {
    setCookie(e.target.value)
  };

  return (
    <Layout>
      <Header>
        <div className="app-header">
          签到统计
        </div>
      </Header>
      <Content>
        <div className="app-content">
          <div className="search">
            统计时间：<RangePicker 
              defaultValue={[moment(searchParams.startDate, dateFormat), moment(searchParams.endDate, dateFormat)]}
              onOpenChange={handleOpenChange}
              onChange={(date) => handleDateChange(date)}/>
             <Button type="primary" onClick={showModal}>设置cookie</Button>
          </div>
          <Table
            loading={loading}
            columns={columns}
            dataSource={tableData}
            bordered
            title={() => `我的签到记录表（总工时：${totalTime.toFixed(2)}；正常工作时长：${nomalWorkDay*8}；
              超出工作时长：${(totalTime-nomalWorkDay*8).toFixed(2)}）`}
            rowKey="id"
            scroll={{x: 1300}}
          />
        </div>
      </Content>
      <Modal title="设置cookie" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <TextArea placeholder="请输入cookie" allowClear value={cookie} onChange={onChange} rows={6} />
      </Modal>
    </Layout>
  );
}

export default App;
